package com.bawei.auth.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.common.redis.service.RedisService;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.user.domain.CusUser;
import com.bawei.mall.user.remote.RemoteUserInfo;
import com.bawei.system.domain.model.LoginUser;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class SysUserService {
    @Autowired
    private RemoteUserInfo remoteUserService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisService redisService;


    private static final String ACCESS_TOKEN="login_tokens:";

    public LoginUser login(String username, String password) {
        if(StringUtils.isEmpty(username)){
            throw new RuntimeException("用户名不能为空");
        }
        if(StringUtils.isEmpty(password)){
            throw new RuntimeException("密码不能为空");
        }

        R<CusUser> byName = remoteUserService.findByName(username);
        CusUser data = byName.getData();
        if(data==null){
            throw new RuntimeException("用户不存在");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setCusUser(data);
        return loginUser;
    }

    public R<CusUser> getInfo() {
//        redisService.getCacheObject(SecurityUtils.getToken());
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        String cusUserJSONString = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser= JSON.parseObject(cusUserJSONString, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        return R.ok(cusUser);
    }

    private String getTokenKey(String key) {
        return ACCESS_TOKEN + key;
    }

//    private String getTokenKey(String token)
//    {
//
//    }
}
